package org.bysun.ggcip.parse;

import org.apache.commons.io.IOUtils;
import org.bysun.ggcip.Commons;

import java.util.*;

/**
 * User: bysun
 * Date: 2014/6/7 0007
 * Time: 13:00
 */
public class IpAddrParse {

    /**
     * 获取gccip列表
     *
     * @return ip列表文件
     */
    public static Map<String, Set<String>> parse() {
        try {
            Map<String, Set<String>> result = new HashMap<>();
            List<String> ipstr = IOUtils.readLines(
                IpAddrParse.class.getClassLoader().getResourceAsStream("gccips.csv"),
                    Commons.ENCODE
            );

            for (String s : ipstr) {
                String[] infos = s.split(",");
                String name = infos[0].toLowerCase();
                Set<String> ips = result.get(name);
                if (null == ips) {
                    ips = new HashSet<>();
                    result.put(name, ips);
                }
                String prefix = infos[1];
                int min = Integer.parseInt(infos[2]);
                int max = Integer.parseInt(infos[3]);
                for (int i = min; i <= max; i++) {
                    ips.add(prefix + "." + i);
                }
            }
            return result;
        } catch (Throwable e) {
            throw new RuntimeException("无法生成IP地址列表", e);
        }
    }
}
